<template>
  <div class="invoice-page">
    <el-page-header title="返回" content="发票信息" class="page-header" />
    
    <el-card class="filter-card">
      <el-form :model="filterForm" label-width="80px" inline>
        <el-form-item label="发票类型">
          <el-select v-model="filterForm.invoiceType" placeholder="请选择发票类型" style="width: 150px;">
            <el-option label="全部" value=""></el-option>
            <el-option label="进项发票" value="incoming"></el-option>
            <el-option label="销项发票" value="outgoing"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发票号码">
          <el-input v-model="filterForm.invoiceNumber" placeholder="请输入发票号码" style="width: 150px;" />
        </el-form-item>
        <el-form-item label="开票日期">
          <el-date-picker
            v-model="filterForm.invoiceDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="list-card">
      <template #header>
        <div class="list-header">
          <span>发票列表</span>
          <div class="list-actions">
            <el-button type="primary" @click="handleAdd">新增</el-button>
            <el-button @click="handleImport">导入</el-button>
            <el-button @click="handleExport">导出</el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="invoiceList"
        v-loading="loading"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="invoiceNumber" label="发票号码" min-width="120" />
        <el-table-column prop="invoiceCode" label="发票代码" min-width="100" />
        <el-table-column prop="sellerName" label="销方名称" min-width="150" />
        <el-table-column prop="buyerName" label="购方名称" min-width="150" />
        <el-table-column prop="totalAmount" label="金额" min-width="100" align="right">
          <template #default="{ row }">
            ¥{{ formatAmount(row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="taxAmount" label="税额" min-width="100" align="right">
          <template #default="{ row }">
            ¥{{ formatAmount(row.taxAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalTaxAmount" label="价税合计" min-width="120" align="right">
          <template #default="{ row }">
            ¥{{ formatAmount(row.totalTaxAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="invoiceDate" label="开票日期" width="120" />
        <el-table-column prop="invoiceType" label="发票类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.invoiceType === 'incoming' ? 'primary' : 'success'">
              {{ row.invoiceType === 'incoming' ? '进项' : '销项' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">查看</el-button>
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 发票详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="currentInvoice?.invoiceType === 'incoming' ? '进项发票详情' : '销项发票详情'"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="发票类型">
          <el-tag :type="currentInvoice?.invoiceType === 'incoming' ? 'primary' : 'success'">
            {{ currentInvoice?.invoiceType === 'incoming' ? '进项发票' : '销项发票' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="发票号码">{{ currentInvoice?.invoiceNumber }}</el-descriptions-item>
        <el-descriptions-item label="发票代码">{{ currentInvoice?.invoiceCode }}</el-descriptions-item>
        <el-descriptions-item label="销方名称">{{ currentInvoice?.sellerName }}</el-descriptions-item>
        <el-descriptions-item label="购方名称">{{ currentInvoice?.buyerName }}</el-descriptions-item>
        <el-descriptions-item label="金额">¥{{ formatAmount(currentInvoice?.totalAmount) }}</el-descriptions-item>
        <el-descriptions-item label="税额">¥{{ formatAmount(currentInvoice?.taxAmount) }}</el-descriptions-item>
        <el-descriptions-item label="价税合计">¥{{ formatAmount(currentInvoice?.totalTaxAmount) }}</el-descriptions-item>
        <el-descriptions-item label="开票日期">{{ currentInvoice?.invoiceDate }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentInvoice?.status)">
            {{ getStatusText(currentInvoice?.status) }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="openSaasPortal">在SaaS端查看详情</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 加载状态
const loading = ref(false)

// 筛选表单
const filterForm = reactive({
  invoiceType: '',
  invoiceNumber: '',
  invoiceDateRange: []
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 发票列表
const invoiceList = ref([])

// 选中的发票
const selectedInvoices = ref([])

// 详情对话框
const detailDialogVisible = ref(false)
const currentInvoice = ref(null)

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'normal': return 'success'
    case 'void': return 'danger'
    case 'draft': return 'warning'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'normal': return '正常'
    case 'void': return '已作废'
    case 'draft': return '草稿'
    default: return '未知'
  }
}

// 格式化金额
const formatAmount = (amount) => {
  return amount ? parseFloat(amount).toFixed(2) : '0.00'
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getInvoiceList()
}

// 重置
const handleReset = () => {
  filterForm.invoiceType = ''
  filterForm.invoiceNumber = ''
  filterForm.invoiceDateRange = []
  pagination.currentPage = 1
  getInvoiceList()
}

// 新增
const handleAdd = () => {
  ElMessage.info('请在SaaS端进行新增操作')
}

// 导入
const handleImport = () => {
  ElMessage.info('请在SaaS端进行导入操作')
}

// 导出
const handleExport = () => {
  ElMessage.info('请在SaaS端进行导出操作')
}

// 查看
const handleView = (row) => {
  currentInvoice.value = row
  detailDialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  ElMessage.info('请在SaaS端进行编辑操作')
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除发票号码为 ${row.invoiceNumber} 的发票吗？`,
    '删除确认',
    {
      type: 'warning'
    }
  ).then(() => {
    ElMessage.info('请在SaaS端进行删除操作')
  }).catch(() => {
    // 取消删除
  })
}

// 选中项变化
const handleSelectionChange = (selection) => {
  selectedInvoices.value = selection
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  getInvoiceList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  getInvoiceList()
}

// 获取发票列表
const getInvoiceList = async () => {
  loading.value = true
  try {
    // 从Chrome存储中获取发票数据
    const result = await new Promise((resolve) => {
      chrome.storage.local.get(['capturedRequests'], (result) => {
        resolve(result)
      })
    })
    
    const allRequests = Array.isArray(result.capturedRequests) ? result.capturedRequests : []
    
    // 筛选出发票数据（根据URL或数据类型）
    const invoiceRequests = allRequests.filter(request => {
      // 根据拦截规则匹配发票数据
      return request.url && (
        request.url.includes('invoice') || 
        request.url.includes('fapiao') ||
        (request.dataType && (request.dataType === 'incomingInvoice' || request.dataType === 'outgoingInvoice'))
      )
    })
    
    // 处理数据格式
    const formattedInvoices = invoiceRequests.map((request, index) => {
      // 尝试解析响应数据
      let invoiceData = {}
      try {
        if (request.response) {
          invoiceData = typeof request.response === 'string' ? JSON.parse(request.response) : request.response
        } else if (request.requestBody) {
          invoiceData = typeof request.requestBody === 'string' ? JSON.parse(request.requestBody) : request.requestBody
        }
      } catch (e) {
        console.error('解析发票数据失败:', e)
      }
      
      // 确定发票类型
      let invoiceType = 'outgoing' // 默认为销项发票
      if (request.dataType === 'incomingInvoice' || 
          (request.url && (request.url.includes('incoming') || request.url.includes('qlfpcx')))) {
        invoiceType = 'incoming' // 进项发票
      } else if (request.dataType === 'outgoingInvoice' || 
                 (request.url && (request.url.includes('outgoing') || request.url.includes('fpxxcx')))) {
        invoiceType = 'outgoing' // 销项发票
      }
      
      return {
        id: request.id || index + 1,
        invoiceNumber: invoiceData['invoiceNumber'] || invoiceData['fpdm'] || '未知',
        invoiceCode: invoiceData['invoiceCode'] || invoiceData['fphm'] || '',
        sellerName: invoiceData['sellerName'] || invoiceData['xfmc'] || '未知销方',
        buyerName: invoiceData['buyerName'] || invoiceData['gfmc'] || '未知购方',
        totalAmount: invoiceData['totalAmount'] || invoiceData['je'] || '0.00',
        taxAmount: invoiceData['taxAmount'] || invoiceData['se'] || '0.00',
        totalTaxAmount: invoiceData['totalTaxAmount'] || invoiceData['jshj'] || '0.00',
        invoiceDate: invoiceData['invoiceDate'] || invoiceData['kprq'] || new Date(request.timestamp || Date.now()).toISOString().split('T')[0],
        invoiceType: invoiceType,
        status: request.synced ? 'normal' : 'draft'
      }
    })
    
    // 应用筛选条件
    let filteredInvoices = formattedInvoices
    if (filterForm.invoiceType) {
      filteredInvoices = filteredInvoices.filter(invoice => invoice.invoiceType === filterForm.invoiceType)
    }
    if (filterForm.invoiceNumber) {
      filteredInvoices = filteredInvoices.filter(invoice => 
        invoice.invoiceNumber.includes(filterForm.invoiceNumber)
      )
    }
    
    // 分页处理
    pagination.total = filteredInvoices.length
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    invoiceList.value = filteredInvoices.slice(start, end)
  } catch (error) {
    console.error('获取发票列表失败:', error)
    ElMessage.error('获取发票列表失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 打开SaaS门户
const openSaasPortal = () => {
  // 在实际应用中，这里应该打开对应的SaaS端页面
  window.open('http://localhost:4000/finance/invoices', '_blank')
}

// 组件挂载时获取数据
onMounted(() => {
  getInvoiceList()
})
</script>

<style scoped>
.invoice-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.list-card {
  min-height: calc(100vh - 240px);
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>